/**
 * <pre>
 * Title: 		SchedulingListenerEvent.java
 * Project: 	HP-Common
 * Type:		com.hengpeng.common.listener.SchedulingListenerEvent
 * Author:		linriqing
 * Create:	 	2007-6-8 下午03:58:05
 * Copyright: 	Copyright (c) 2007
 * Company:
 * <pre>
 */
package com.hengpeng.common.scheduling;

import javax.annotation.PreDestroy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Scheduler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.hengpeng.common.scheduling.quartz.QuartzScheduleExcute;

/**
 * <pre>
 * 任务调度启动暂停事件
 * </pre>
 * @author linriqing
 * @version 1.0, 2007-6-8
 */
@Component
@Lazy(value = false)
public class SchedulingListener implements ApplicationContextAware, DisposableBean
{
	private static final Log logger = LogFactory.getLog(SchedulingListener.class);

	private Scheduler scheduler;

	private ApplicationContext applicationContext;

	@PreDestroy
	public void shutdown()
	{
		try
		{
			scheduler = applicationContext.getBean(Scheduler.class);
		}
		catch (Exception e)
		{
		}
		if (scheduler == null)
		{
			ScheduleExcute.stopAllTask();
		}
		else
		{
			QuartzScheduleExcute.stopAllTask(scheduler);
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
	{
		this.applicationContext = applicationContext;
		try
		{
			scheduler = applicationContext.getBean(Scheduler.class);
		}
		catch (Exception e)
		{
		}
		if (scheduler == null)
		{
			logger.info("Starting scheduling use Custom implement...");
			ScheduleExcute.startAllTask();
		}
		else
		{
			logger.info("Starting scheduling use Quartz implement...");
			QuartzScheduleExcute.startAllTask(scheduler);
		}
	}

	@Override
	public void destroy() throws Exception
	{
		this.shutdown();
	}
}
